<template>
  <div id="AddGoods">
    <el-form :model="goods" label-width="120px">
      <h2>管理商品</h2>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="商品编号" required>
            <el-input
              v-model="goods.goodcode"
              placeholder="请输入商品编号"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品名称" required>
            <el-input
              v-model="goods.goodname"
              placeholder="请输入商品名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品条码">
            <el-input
              v-model="goods.barcode"
              placeholder="请输入商品条码"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="规格型号">
            <el-input
              v-model="goods.specificationmodel"
              placeholder="请输入规格型号"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="首选仓库">
            <el-select v-model="goods.defaultStock">
              <el-option
                v-for="store in storeList"
                :key="store.shId"
                :label="store.storeHomeName"
                :value="store.shId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品类别">
            <el-select v-model="goods.categoryid">
              <el-option
                v-for="category in categorys"
                :key="category.id"
                :label="category.categoryname"
                :value="category.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="计量单位" v-show="!showmultiunitid">
            <el-select v-model="goods.unitid">
              <el-option
                v-for="unit in units"
                :key="unit.id"
                :label="unit.unidname"
                :value="unit.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="多单位">
            <el-checkbox v-model="showmultiunitid"
              ><el-input v-model="ddw" :disabled="!showmultiunitid"></el-input
            ></el-checkbox>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="6" v-show="showmultiunitid">
          <el-form-item label="首选入库单位">
            <el-input v-model="goods.specificationmodel"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-show="showmultiunitid">
          <el-form-item label="首选出库单位">
            <el-input v-model="goods.specificationmodel"></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="6" v-show="showmultiunitid">
          <el-form-item label="整件散包">
            <el-input v-model="zjsb"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="产地">
            <el-input
              v-model="goods.origin"
              placeholder="请输入产地"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="注册证号">
            <el-input
              v-model="goods.registrationnumber"
              placeholder="请输入注册证号"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生产许可证">
            <el-input
              v-model="goods.productionlicense"
              placeholder="请输入生产许可证"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="默认供应商">
            <el-input
              v-model="goods.suppliercode"
              placeholder="请输入默认供应商"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="品牌">
            <el-select v-model="goods.brandid" placeholder="请选择品牌">
              <el-option
                v-for="brand in brands"
                :key="brand.id"
                :label="brand.brandname"
                :value="brand.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="重量(kg)">
            <el-input
              v-model="goods.weight"
              placeholder="请输入重量(kg)"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="零售价">
            <el-input v-model="goods.retailprice"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="批发价">
            <el-input v-model="goods.wholesaleprice"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="vip价">
            <el-input v-model="goods.vipprice"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="商品税率">
            <el-input v-model="goods.taxrate"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品开票名称">
            <el-input v-model="goods.invoicename"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品成本价">
            <el-input v-model="goods.unitCost"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <h5 style="position: relative; left: 100px">增加商品图片</h5>
      <el-upload
        style="position: relative; left: 100px"
        class="upload-demo"
        ref="upload"
        action="/erp/goods/goods/upload"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="myFileList"
        :auto-upload="false"
      >
        <el-button slot="trigger" size="small" type="primary"
          >选取文件</el-button
        >
        <el-button
          style="margin-left: 10px"
          size="small"
          type="success"
          @click="submitUpload"
          >上传到服务器</el-button
        >
        <div slot="tip" class="el-upload__tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>

      <el-form-item>
        <el-checkbox v-model="enableWarehouseAlert">仓库预警</el-checkbox>
      </el-form-item>

      <el-row :gutter="20" style="width: 100%; position: relative; left: 150px">
        <el-col :span="6">
          <el-form-item v-if="enableWarehouseAlert" label="最低库存">
            <el-input
              v-model="goods.lowStock"
              placeholder="请输入最低库存"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item v-if="enableWarehouseAlert" label="最高库存">
            <el-input
              v-model="goods.heightStock"
              placeholder="请输入最高库存"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-checkbox v-model="showSettings">设置商品辅助属性</el-checkbox>
      </el-form-item>

      <div
        v-if="showSettings"
        style="width: 100%; position: relative; left: 150px"
      >
        <!-- <el-form-item label="商品辅助属性">
          <el-checkbox-group v-model="goods.attributeCategories">
            <el-checkbox label="颜色" value="颜色"></el-checkbox>
            <el-checkbox label="品牌" value="品牌"></el-checkbox>
            <el-checkbox label="规格" value="规格"></el-checkbox>
            <el-checkbox label="尺码" value="尺码"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          v-if="goods.attributeCategories.includes('颜色')"
          label="颜色"
        >
          <el-checkbox-group v-model="goods.colors">
            <el-checkbox label="红" value="红"></el-checkbox>
            <el-checkbox label="绿" value="绿"></el-checkbox>
            <el-checkbox label="蓝" value="蓝"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="goods.zuhe">自动建立属性组合</el-checkbox>
        </el-form-item>
        <el-button
          type="primary"
          v-if="goods.zuhe"
          @click="generateAttributeCombinations"
          >快速生成</el-button
        >
        <el-table
          :data="attributeCombinations"
          v-if="goods.zuhe"
          style="width: 100%"
        >
          <el-table-column prop="image" label="图片"></el-table-column>
          <el-table-column prop="color" label="颜色" required></el-table-column>
          <el-table-column
            prop="attributeCode"
            label="属性编号"
            required
          ></el-table-column>
          <el-table-column
            prop="attributeBarcode"
            label="属性条码"
          ></el-table-column>
          <el-table-column
            prop="wholesalePrice"
            label="批发价"
          ></el-table-column>
          <el-table-column
            prop="discount1"
            label="折扣率1(%)"
          ></el-table-column>
          <el-table-column prop="vipPrice" label="VIP会员价"></el-table-column>
          <el-table-column prop="retailPrice" label="零售价"></el-table-column>
          <el-table-column
            prop="discount2"
            label="折扣率2(%)"
          ></el-table-column>
          <el-table-column prop="price1" label="价格1"></el-table-column>
        </el-table> -->
      </div>

      <el-form-item>
        <el-checkbox v-model="enableShelfLifeManagement"
          >启用批次保质期管理</el-checkbox
        >
      </el-form-item>
      <div v-if="enableShelfLifeManagement">
        <el-row
          :gutter="20"
          style="width: 100%; position: relative; left: 150px"
        >
          <el-col :span="6">
            <el-form-item label="保质期天数">
              <el-input
                v-model="goods.shelfLifeDays"
                placeholder="请输入保质期天数"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报警天数">
              <el-input
                v-model="goods.alertDays"
                placeholder="请输入报警天数"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <el-form-item>
        <el-checkbox v-model="enableSerialNumberManagement"
          >启用序列号管理</el-checkbox
        >
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "AddGoods",
  data() {
    return {
      ddw: "",
      zjsb: "",
      enableSerialNumberManagement: "",
      enableShelfLifeManagement: "",
      showmultiunitid: "",
      enableWarehouseAlert: false,
      goods: {
        lowStock: "",
        heightStock: "",
        goodattributeid: "",
        id: null,
        brandName: "",
        categoryName: "",
        basicUnitName: "",
        defaultStock: 1,
        defaultStockName: "",
        imagename: "",
        goodcode: "",
        goodname: "",
        initNum: 0,
        initPrice: 0,
        barcode: "",
        specificationmodel: "",
        categoryid: null,
        warehouseid: null,
        unitid: null,
        multiunitid: null,
        origin: "",
        registrationnumber: "",
        productionlicense: "",
        suppliercode: "",
        brandid: null,
        unitCost: 0,
        weight: 0,
        retailprice: 0,
        wholesaleprice: 0,
        vipprice: 0,
        taxrate: 0,
        invoicename: "",
        invoicenotes: "",
        managementmethod: null,
        shelflifedays: null,
        createDate: null,
        itStatus: 0,
      },

      brands: [],
      attributes: [],
      units: [],
      stocks: [],
      categorys: [],
      storeList: [],
      attributesOptions: [],
      showSettings: false,
      myFileList: [],
    };
  },
  watch: {
    enableSerialNumberManagement(newValue) {
      if (newValue) {
        this.enableShelfLifeManagement = false;
      }
    },
    enableShelfLifeManagement(newValue) {
      if (newValue) {
        this.enableSerialNumberManagement = false;
      }
    },
  },
  methods: {
    validateData() {
      let errors = [];

      // 验证必填字段
      if (!this.goods.goodcode) {
        errors.push("商品编号不能为空。");
      }
      if (!this.goods.goodname) {
        errors.push("商品名称不能为空。");
      }
      if (!this.goods.defaultStock) {
        errors.push("首选仓库不能为空。");
      }
      if (!this.goods.categoryid) {
        errors.push("商品类别不能为空。");
      }
      if (!this.goods.unitid) {
        errors.push("计量单位不能为空。");
      }
      if (!this.goods.origin) {
        errors.push("产地不能为空。");
      }
      if (!this.goods.registrationnumber) {
        errors.push("注册证号不能为空。");
      }
      if (!this.goods.productionlicense) {
        errors.push("生产许可证不能为空。");
      }
      if (!this.goods.suppliercode) {
        errors.push("默认供应商不能为空。");
      }
      if (!this.goods.brandid) {
        errors.push("品牌不能为空。");
      }
      if (!this.goods.weight) {
        errors.push("重量不能为空。");
      }
      if (!this.goods.retailprice) {
        errors.push("零售价不能为空。");
      }
      if (!this.goods.wholesaleprice) {
        errors.push("批发价不能为空。");
      }
      if (!this.goods.vipprice) {
        errors.push("VIP价不能为空。");
      }
      if (!this.goods.taxrate) {
        errors.push("商品税率不能为空。");
      }
      if (!this.goods.invoicename) {
        errors.push("商品开票名称不能为空。");
      }
      if (!this.goods.unitCost) {
        errors.push("商品成本价不能为空。");
      }

      // 验证数字字段
      if (this.goods.weight && isNaN(this.goods.weight)) {
        errors.push("重量必须是数字。");
      } else if (
        this.goods.weight &&
        !/^\d+(\.\d{1,2})?$/.test(this.goods.weight)
      ) {
        errors.push("重量应保留两位小数。");
      }

      if (this.goods.retailprice && isNaN(this.goods.retailprice)) {
        errors.push("零售价必须是数字。");
      } else if (
        this.goods.retailprice &&
        !/^\d+(\.\d{1,2})?$/.test(this.goods.retailprice)
      ) {
        errors.push("零售价应保留两位小数。");
      }

      if (this.goods.wholesaleprice && isNaN(this.goods.wholesaleprice)) {
        errors.push("批发价必须是数字。");
      } else if (
        this.goods.wholesaleprice &&
        !/^\d+(\.\d{1,2})?$/.test(this.goods.wholesaleprice)
      ) {
        errors.push("批发价应保留两位小数。");
      }

      if (this.goods.vipprice && isNaN(this.goods.vipprice)) {
        errors.push("VIP价必须是数字。");
      } else if (
        this.goods.vipprice &&
        !/^\d+(\.\d{1,2})?$/.test(this.goods.vipprice)
      ) {
        errors.push("VIP价应保留两位小数。");
      }

      if (this.goods.taxrate && isNaN(this.goods.taxrate)) {
        errors.push("商品税率必须是数字。");
      } else if (
        this.goods.taxrate &&
        !/^\d+(\.\d{1,2})?$/.test(this.goods.taxrate)
      ) {
        errors.push("商品税率应保留两位小数。");
      }

      if (this.goods.unitCost && isNaN(this.goods.unitCost)) {
        errors.push("商品成本价必须是数字。");
      } else if (
        this.goods.unitCost &&
        !/^\d+(\.\d{1,2})?$/.test(this.goods.unitCost)
      ) {
        errors.push("商品成本价应保留两位小数。");
      }

      // 验证条件性字段
      if (this.enableWarehouseAlert) {
        if (!this.goods.lowStock) {
          errors.push("最低库存不能为空。");
        } else if (isNaN(this.goods.lowStock)) {
          errors.push("最低库存必须是数字。");
        } else if (!/^\d+(\.\d{1,2})?$/.test(this.goods.lowStock)) {
          errors.push("最低库存应保留两位小数。");
        }

        if (!this.goods.heightStock) {
          errors.push("最高库存不能为空。");
        } else if (isNaN(this.goods.heightStock)) {
          errors.push("最高库存必须是数字。");
        } else if (!/^\d+(\.\d{1,2})?$/.test(this.goods.heightStock)) {
          errors.push("最高库存应保留两位小数。");
        }
      }

      if (this.enableShelfLifeManagement) {
        if (!this.goods.shelfLifeDays) {
          errors.push("保质期天数不能为空。");
        } else if (isNaN(this.goods.shelfLifeDays)) {
          errors.push("保质期天数必须是数字。");
        }

        if (!this.goods.alertDays) {
          errors.push("报警天数不能为空。");
        } else if (isNaN(this.goods.alertDays)) {
          errors.push("报警天数必须是数字。");
        }
      }

      if (errors.length > 0) {
        alert(errors.join("\n"));
        return false;
      }

      return true;
    },
    getMulitiUnit() {
      this.axios({
        url: "/erp/goods/multiUnit/getList",
      }).then((rs) => {
        this.munits = rs.data.list;
        console.log("munits", this.munits);
      });
    },

    generateRandomNumber(length) {
      const characters = "0123456789";
      let result = "";
      for (let i = 0; i < length; i++) {
        result += characters.charAt(
          Math.floor(Math.random() * characters.length)
        );
      }
      return result;
    },
    getFileExtension(filename) {
      return filename.split(".").pop();
    },

    submitForm() {
      if (!this.validateData()) {
        return;
      }
      var fileNames = "";
      var fileList = this.$refs.upload.uploadFiles;
      fileList.forEach((element) => {
        fileNames = fileNames + element.name + ",";
      });
      console.log(fileNames);
      this.$refs.upload.uploadFiles = fileList;
      console.log(this.$refs.upload);
      this.$refs.upload.submit();
      this.goods.imagename = fileNames;
      if (this.enableSerialNumberManagement == true) {
        this.goods.managementmethod = 1;
      }
      if (this.enableShelfLifeManagement == true) {
        this.goods.managementmethod = 2;
      }
      if (this.goods.id == "") {
        this.axios({
          url: "/erp/goods/goods/addGoods",
          method: "POST",
          data: {
            ...this.goods,
          },
        }).then((rs) => {
          if (rs.data.itStatus == true) {
            alert("新增成功！");
            this.goto("Goods");
          } else {
            alert("新增失败");
          }
        });
      } else {
        this.axios({
          url: "/erp/goods/goods/updateGoods",
          method: "POST",
          data: {
            ...this.goods,
          },
        }).then((rs) => {
          if (rs.data.itStatus == true) {
            alert("修改成功！");
            this.goto("Goods");
          } else {
            alert("修改失败");
          }
        });
      }
    },
    getStoreList() {
      this.axios
        .get("/info/storeHouse/getAllStore", {
          params: {
            cId: 1,
          },
        })
        .then((rs) => {
          this.storeList = rs.data.storeList;
        });
    },
    getBrand() {
      this.axios({
        url: "/erp/goods/brand/getAll",
      }).then((rs) => {
        this.brands = rs.data.list;
      });
    },
    getGoods(id) {
      this.axios({
        url: "/erp/goods/goods/getGoods",
        params: {
          id,
        },
      }).then((rs) => {
        this.goods = rs.data.goods;
      });
    },
    goto(to) {
      this.$router.push(to);
    },
    getAttribute() {
      this.axios({
        url: "/erp/goods/attributes/getList",
        params: {
          pageSize: 5,
          pageNum: 1,
        },
      }).then((rs) => {
        this.attributes = rs.data.list;
      });
    },
    getUnit() {
      this.axios({
        url: "/erp/goods/basicUnit/getList",
        params: {
          pageSize: 5,
          pageNum: 1,
        },
      }).then((rs) => {
        this.units = rs.data.list;
      });
    },
    getCategory() {
      this.axios({
        url: "/erp/goods/category/getList",
        params: {
          pageSize: 5,
          pageNum: 1,
        },
      })
        .then((rs) => {
          this.categorys = rs.data.list;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleRemove(file, myFileList) {
      console.log(file, myFileList);
    },
    handlePreview(file) {
      console.log(file);
    },
  },
  created() {
    var id = this.$route.params.id;
    if (typeof id === "undefined") {
      this.goods.id = "";
    } else {
      this.goods.id = id;
      this.getGoods(id);
    }
    this.getMulitiUnit();
    this.getStoreList();
    this.getAttribute();
    this.getBrand();
    this.getCategory();
    this.getUnit();
  },
};
</script>

<style scoped>
.table-header-row {
  background-color: #f5f7fa; /* 例如，使用浅灰色作为背景 */
}
.el-table th,
.el-table td {
  text-align: center;
}
#AddProduct {
  padding: 20px;
}

.box-card {
  width: 800px;
  margin: 0 auto;
}

h2,
h3 {
  margin-bottom: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  background-color: gray; /* 设置背景颜色为灰色 */
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  position: relative;
  left: 100px;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  background-color: gray; /* 设置背景颜色为灰色 */
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  position: relative;
  left: 100px;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>